package com.example.SOPVersionChain.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.example.SOPVersionChain.model.FileInfo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import jakarta.annotation.PostConstruct;
import org.springframework.util.StringUtils;

@Service
public class FileService {
    
    @Value("${version.file.directory}")
    private String fileDirectory;
    
    // 在Spring初始化后检查并创建目录
    @PostConstruct
    public void init() {
        try {
            File directory = new File(fileDirectory);
            if (!directory.exists()) {
                boolean created = directory.mkdirs();
                System.out.println("目录不存在，尝试创建：" + fileDirectory + " - 结果：" + (created ? "成功" : "失败"));
            } else {
                System.out.println("目录存在：" + fileDirectory);
                System.out.println("目录是否可读：" + directory.canRead());
                System.out.println("目录是否可写：" + directory.canWrite());
            }
        } catch (Exception e) {
            System.err.println("初始化目录时出错：" + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 获取目录下的所有文件
     * @return 文件列表，包含文件名和最后修改时间
     */
    public List<FileInfo> getAllFiles() {
        List<FileInfo> fileList = new ArrayList<>();
        try {
            // 确保路径不包含额外的引号或空格
            String cleanPath = fileDirectory.trim();
            File directory = new File(cleanPath);
            
            System.out.println("正在读取目录：" + cleanPath);
            
            if (directory.exists() && directory.isDirectory()) {
                File[] files = directory.listFiles();
                if (files != null) {
                    for (File file : files) {
                        if (file.isFile()) {
                            FileInfo fileInfo = new FileInfo();
                            fileInfo.setFileName(file.getName());
                            fileInfo.setLastModified(new Date(file.lastModified()));
                            fileInfo.setSize(file.length());
                            fileList.add(fileInfo);
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("读取文件列表时出错：" + e.getMessage());
            e.printStackTrace();
        }
        
        return fileList;
    }
    
    /**
     * 获取文件的完整路径
     * @param fileName 文件名
     * @return 文件的完整路径
     */
    public String getFilePath(String fileName) {
        return fileDirectory + File.separator + fileName;
    }
    
    /**
     * 获取配置的目录路径
     */
    public String getDirectoryPath() {
        return fileDirectory;
    }
    
    /**
     * 检查目录是否存在并可访问
     */
    public boolean isDirectoryAccessible() {
        File directory = new File(fileDirectory);
        return directory.exists() && directory.isDirectory() && directory.canRead();
    }
} 